﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using Utils.DC.Web.UI;
using System.Data;
using System.Web.UI;
using Utils.Entity;
using System.Web.Configuration;
using System.IO;
using System.Web;

namespace Utils.DCSControl
{
    /// <summary>
    /// Class ke thua tu System.Web.Page
    /// Viet them cac properties cua page
    /// Cac ham lay ve user control
    /// Cac ham check quyen
    /// Author: Dao Xuan Trung
    /// Modified Date: 18/01/2010
    /// </summary>
    public abstract class dcPage : System.Web.UI.Page
    {
        public CartEntity Cart
        {
            get 
            {
                if (Session["Cart"] == null)
                {
                    CartEntity cartEntity = new CartEntity();
                    //cartEntity.UsersID = this.CurrentUser.UserID;
                    //cartEntity.UserName = this.CurrentUser.UserName;
                    cartEntity.ListProduct = new ArrayList();
                    Session["Cart"] = cartEntity;
                }
                return (CartEntity)Session["Cart"]; 
            }
            set 
            { 
                Session["Cart"] = value; 
            }
        }

        public String Lang
        {
            get { return Session["Lang"] != null ? Session["Lang"].ToString() : "vn"; }
            set { Session["Lang"] = value; }
        }


        protected PageSettings pageSettings = new PageSettings();

        public PageSettings PageSettings
        {
            get
            {
                return pageSettings;
            }
        }

        public UserEntity CurrentUser;

        public dcPage() : base()
        {
        }

        protected void Page_Init(object sender, System.EventArgs e)
        {
            try
            {
                //Compress();
                //Lay ve bien pageSettings chua thong tin cua trang hien tai
                pageSettings = (PageSettings)Context.Items["PageSettings"];

                //Lay ve thong tin cua user neu da dang nhap
                CurrentUser = PageUtility.IsLogin(Session);

                //Neu trang nay la trang hop le (co pagesettings)
                if (pageSettings != null)
                {

                    if (pageSettings.Lang == null || pageSettings.Lang == "")
                    {
                        this.Lang = "vn";
                    }
                    else
                    {
                        this.Lang = pageSettings.Lang.ToLower();
                    }

                    //Lay ve mang cac trang ma ko can check role
                    string[] strs = WebConfigurationManager.AppSettings["UnCheckRolePage"].Split(new char[] { ';' });

                    //Neu trang hien tai nam trong danh sach trang khong phai check role thi load luon module ben trong
                    foreach (string str in strs)
                    {
                        if (Request.RawUrl == str)
                        {
                            LoadModule();
                            return;
                        }
                    }

                    //Neu day la trang cua admin thi check cac role roi moi load module

                    if (pageSettings.IsAdmin)
                    {
                        //Neu dang nhap roi ma co quyen thi load module
                        //if (CurrentUser != null && CheckRole())
                        if (CurrentUser != null)
                        {
                            LoadModule();
                        }
                        else
                        {
                            Response.Redirect(WebConfigurationManager.AppSettings["LoginPage"]);
                        }
                    }
                    else
                    {
                        LoadModule();
                    }

                    //set gia tri title, metakeyword, metadescription
                    
                    this.Title = pageSettings.PageTitle + " " + Format.ConvertToNoSign(pageSettings.PageTitle).Replace('-', ' ');
                    string keyword = pageSettings.MetaKeyword + " " + Format.ConvertToNoSign(pageSettings.MetaKeyword).Replace('-', ' ');
                    string description = pageSettings.MetaDescription + " " + Format.ConvertToNoSign(pageSettings.MetaDescription).Replace('-', ' ');

                    if (this.pageSettings.HasEntry)
                    {
                        try
                        {
                            keyword += this.pageSettings.Entry.Rows[0]["MetaKeyword"].ToString();
                            description = this.pageSettings.Entry.Rows[0]["MetaDescription"].ToString();
                        }
                        catch (Exception ex2)
                        { 
                        }
                    }
                    string meta = "<meta name=\"keywords\" content=\"" + keyword + "\"  />" + "<meta name=\"description\" content=\"" + description + "\"  />";

                    Page.Header.Controls.Add(new LiteralControl(meta));

                }
                else
                {
                    //Neuco config trang default trong webconfig thi redirect sang trang default trong web.config
                    if (WebConfigurationManager.AppSettings["DefaultPage"] != null)
                    {
                        Response.Redirect(WebConfigurationManager.AppSettings["DefaultPage"]);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                Init();
            }
        }

        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (Request.RawUrl != "/")
            {
                Lang = pageSettings.Lang;
            }
            
            //
            Load();
        }

        protected abstract void Load();

        protected abstract void Init();

        internal void Compress()
        {
            HttpContext context = HttpContext.Current;
            HttpRequest request = context.Request;
            string acceptEncoding = request.Headers["Accept-Encoding"];
            HttpResponse response = context.Response;
            if (!string.IsNullOrEmpty(acceptEncoding))
            {
                acceptEncoding = acceptEncoding.ToUpperInvariant();
                if (acceptEncoding.Contains("GZIP"))
                {
                    //response.Filter = new GZipStream(context.Response.Filter, 
                    //CompressionMode.Compress);
                    response.Filter = new WhitespaceFilter(context.Response.Filter,
                                      CompressOptions.GZip);
                    response.AppendHeader("Content-encoding", "gzip");
                }
                else if (acceptEncoding.Contains("DEFLATE"))
                {
                    //response.Filter = new DeflateStream(context.Response.Filter, 
                    //CompressionMode.Compress);
                    response.Filter = new WhitespaceFilter(context.Response.Filter,
                                      CompressOptions.Deflate);
                    response.AppendHeader("Content-encoding", "deflate");
                }
            }
            response.Cache.VaryByHeaders["Accept-Encoding"] = true;
        }

        #region Cac Ham Lam Viec Voi ViewState

        private bool IsCompressViewState()
        {
            try
            {
                if (!this.pageSettings.IsAdmin)
                {
                    if (WebConfigurationManager.AppSettings["NotViewStateCompressPage"].IndexOf(pageSettings.PageAlias) == -1)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                return false;
            }
        }

        protected override object LoadPageStateFromPersistenceMedium()
        {
            if (IsCompressViewState())
            {
                string viewState = Request.Form["__VSTATE"];
                byte[] bytes = Convert.FromBase64String(viewState);
                bytes = WebUtility.Decompress(bytes);
                LosFormatter formatter = new LosFormatter();
                return formatter.Deserialize(Convert.ToBase64String(bytes));
            }
            else
            {
                return base.LoadPageStateFromPersistenceMedium();
            }
        }

        protected override void SavePageStateToPersistenceMedium(object viewState)
        {
            if (IsCompressViewState())
            {
                LosFormatter formatter = new LosFormatter();
                StringWriter writer = new StringWriter();
                formatter.Serialize(writer, viewState);
                string viewStateString = writer.ToString();
                byte[] bytes = Convert.FromBase64String(viewStateString);
                bytes = WebUtility.Compress(bytes);
                ClientScript.RegisterHiddenField("__VSTATE", Convert.ToBase64String(bytes));
            }
            else
            {
                base.SavePageStateToPersistenceMedium(viewState);
            }
        }

        #endregion

        #region Lay ve page hien tai

        private void LoadModule()
        {
            try
            {
                if (pageSettings.IsCache)
                {
                }
                else
                {

                }

                if (pageSettings.ControlPath != null && pageSettings.ControlPath.Trim() != "")
                {
                    Control control = null;
                    if (pageSettings.IsAdmin)
                    {
                        control = this.Master.FindControl("ContentPlaceHolder1").FindControl("ContentPane");
                    }
                    else
                    {
                        control = this.FindControl("ContentPane");
                    }

                    control.Controls.Clear();

                    //TODO bo phan  trong doan + link controlPath
                    try
                    {
                        Control userControl = this.LoadControl(pageSettings.ControlPath);
                        //control.ID = pageSettings.PageAlias;
                        userControl.ID = "module";
                        control.Controls.Add(userControl);
                    }
                    catch (Exception e)
                    {
                        //Response.Write(e.ToString());
                    }
                }
            }
            catch (Exception e)
            {
                //Response.Write(e.ToString());
            }
            //Control pcc = LoadControl("~/WebUserControl1.ascx");

            //// If the control is slated to expire in greater than 60 Seconds
            //if (((PartialCachingControl)pcc).CachedControl != null)
            //{
            //    PartialCachingControl pcc2 = (PartialCachingControl)pcc;
            //    // Make it expire faster. Set a new expiration time to 30 seconds, and make it
            //    // an absolute expiration if it isnt already.        
            //    pcc2.CachePolicy.SetExpires(DateTime.Now.Add(TimeSpan.FromSeconds(30)));
            //    pcc2.CachePolicy.SetSlidingExpiration(false);
            //}
            //Controls.Add(pcc);
        }
        #endregion

        #region Kiem tra quyen

        private bool CheckRole()
        {
            foreach (UserRoleEntity role in CurrentUser.RoleList)
            {
                if (role.PageID == pageSettings.FunctionPageID)
                {
                    return true;
                }
            }
            return false;
        }

        /*
        private bool CheckRole()
        {
            if (pageSettings.RoleList != null)
            {
                IEnumerator ie = pageSettings.RoleList.GetEnumerator();

                if (CurrentUser.RoleList != null)
                {
                    IEnumerator ie2 = CurrentUser.RoleList.GetEnumerator();

                    PageRoleEntity pageRole = null;
                    UserRoleEntity userRole = null;

                    while (ie.MoveNext())
                    {
                        pageRole = (PageRoleEntity)ie.Current;
                        ie2.Reset();
                        while (ie2.MoveNext())
                        {
                            userRole = (UserRoleEntity)ie2.Current;
                            if (userRole.RoleID == pageRole.RoleID)
                            {
                                return true;
                            }
                        }
                    }
                    return false;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return true;
            }
        }
        */

        public void CheckLogin()
        {

            //Lay ve mang cac trang ma ko can check role
            string[] strs = WebConfigurationManager.AppSettings["UnCheckRolePage"].Split(new char[] { ';' });

            //Neu trang hien tai nam trong danh sach trang khong phai check role thi load luon module ben trong
            foreach (string str in strs)
            {
                if (Request.RawUrl == str)
                {
                    return;   
                }
            }

            //Neu chua dang nhap thi redirect ve trang dang nhap
            if (CurrentUser == null)
            {
                Response.Redirect(WebConfigurationManager.AppSettings["LoginPage"]);
            }
        }

        #endregion

        #region Cac Ham Lam Viec Voi Gio Hang

       
        #endregion
    }
}
